<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>错题本</title>
    <!-- Font Awesome 图标 -->
    <link rel="stylesheet" href="../../static/css/all.min.css">
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3f37c9;
            --border-radius: 8px;
            --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            --border-color: #e0e0e0;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', sans-serif;
            background-color: #f5f7fa;
            padding: 20px;
        }

        .container {
            max-width: 1250px;
            margin: 0 auto;
            background: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            overflow: hidden;
        }

        /* 表格样式 */
        .error-notes-table {
            width: 100%;
            text-align: center;
            border-collapse: collapse;
        }

        .error-notes-table th,
        .error-notes-table td {
            padding: 12px 15px;
            text-align: center;
            border-bottom: 1px solid var(--border-color);
        }

        .error-notes-table th {
            background-color: var(--primary-color);
            color: white;
        }

        /* 操作按钮 */
        .action-btn {
            padding: 6px 10px;
            margin-right: 5px;
            border: 1px solid var(--border-color);
            border-radius: var(--border-radius);
            background: none;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }

        .action-btn i {
            margin-right: 4px;
            font-size: 14px;
        }

        .action-btn:hover {
            background: linear-gradient(120deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            border-color: transparent;
            color: #fff;
            box-shadow: 0 4px 12px rgba(67, 97, 238, 0.2);
            transform: translateY(-1px);
        }

        .action-btn:active {
            transform: translateY(1px) scale(0.98);
            box-shadow: none;
        }

        .delete-btn {
            border-color: #ff4757;
        }

        .delete-btn:hover {
            background: linear-gradient(120deg, #ff4757 0%, #ff6b81 100%);
            box-shadow: 0 4px 12px rgba(255, 71, 87, 0.2);
        }

        /* 分页器 */
        .pagination-container {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            padding: 20px;
            background: white;
            border-top: 1px solid var(--border-color);
            gap: 10px;
        }

        .pagination-controls {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .page-number {
            display: flex;
            gap: 5px;
        }

        .page-btn {
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            background: none;
            cursor: pointer;
            transition: all 0.2s;
        }

        .page-btn:hover {
            border-color: var(--primary-color);
            color: var(--primary-color);
        }

        .page-btn.active {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
            color: white;
        }

        .page-btn.disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .page-input {
            width: 60px;
            height: 36px;
            text-align: center;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            margin: 0 10px;
        }

        .page-size-selector {
            margin-left: 10px;
        }

        .page-size-select {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 3px;
            background: #fff;
            cursor: pointer;
            outline: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
            background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right 8px center;
            background-size: 16px;
            padding-right: 28px;
        }

        .change {
            width: 50px;
        }

        /* 查看弹层 */
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .modal-content {
            background-color: white;
            padding: 25px;
            border-radius: var(--border-radius);
            width: 600px;
            position: relative;
        }

        .modal-close {
            position: absolute;
            top: 15px;
            right: 20px;
            font-size: 24px;
            cursor: pointer;
            color: #999;
        }

        .modal h3 {
            margin-bottom: 20px;
            color: #2c3e50;
        }

        .modal p {
            margin-bottom: 10px;
            line-height: 1.6;
        }
        .caozuo{
            width: 200px !important;
        }
        /* 顶部操作栏 */
        .toolbar {
            padding: 20px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .btn {
            padding: 10px 16px;
            border: none;
            border-radius: var(--border-radius);
            background-color: var(--primary-color);
            color: white;
            cursor: pointer;
            display: flex;
            align-items: center;
        }

        .btn i, .search-btn i {
            margin-right: 8px;
        }
        input[type="checkbox"] {
            width: 16px;
            height: 16px;
            cursor: pointer;
        }

    </style>
</head>

<body>
<div class="container">
    <div class="toolbar">
        <button class="btn" id="addNoteBtn">
            <i class="fas fa-plus"></i> 添加考试
        </button>
    </div>

    <!-- 错题表格 -->
    <table class="error-notes-table">
        <thead>
        <tr>
            <th width="50px">
                <input type="checkbox" id="selectAll" onclick="toggleSelectAll()">
            </th>
            <th width="60px">序号</th>
            <th>题干</th>
            <th>正确答案</th>
            <th>错误原因</th>
            <th>我的错误答案</th>
            <th class="caozuo">操作</th>
        </tr>
        </thead>
        <tbody id="errorNotesTableBody"></tbody>
    </table>

    <!-- 分页器 -->
    <div class="pagination-container">
        <div class="pagination-controls">
            <button class="page-btn first" onclick="goToPage(1)">
                <i class="fas fa-angle-double-left"></i>
            </button>
            <button class="page-btn front" onclick="goToPage(currentPage - 1)">
                <i class="fas fa-angle-left"></i>
            </button>
            <div class="page-number" id="pageNumber"></div>
            <button class="page-btn next" onclick="goToPage(currentPage + 1)">
                <i class="fas fa-angle-right"></i>
            </button>
            <button class="page-btn end" onclick="goToPage(totalPages)">
                <i class="fas fa-angle-double-right"></i>
            </button>
        </div>
        <div class="page-size-selector">
            <select class="page-size-select" onchange="changePageSize()">
                <option value="5">5条/页</option>
                <option value="10">10条/页</option>
                <option value="20">20条/页</option>
            </select>
        </div>
        <input type="number" class="page-input" id="pageJump" placeholder="页码" min="1" onchange="jumpToPage()">
        <button class="page-btn change" onclick="jumpToPage()">跳转</button>
    </div>


</div>

<!-- 查看错题弹层 -->
<div class="modal" id="viewErrorNoteModal">
    <div class="modal-content">
        <span class="modal-close" onclick="closeModal()">&times;</span>
        <h3>错题详情</h3>
        <p><strong>ID：</strong><span id="viewNoteId"></span></p>
        <p><strong>问题：</strong><span id="viewQuestion"></span></p>
        <p><strong>正确答案：</strong><span id="viewCorrectAnswer"></span></p>
        <p><strong>错误原因：</strong><span id="viewErrorReason"></span></p>
        <p><strong>我的错误答案：</strong><span id="viewUserAnswer"></span></p>
    </div>
</div>

<script src="../../static/js/jquery.js"></script>
<script src="../../static/js/jquery.cookie.js"></script>

<script>
    // 分页参数
    let currentPage = 1;      // 当前页码
    let pageSize = 5;         // 每页条数
    let totalPages = 0;       // 总页数
    let totalItems = 0;       // 总数据量
    let student = $.cookie("studentName"); // 从 cookie 获取学生信息
    // 全选/取消全选
    // 全局变量存储所有已选ID（跨分页）
    let globalSelectedIds = new Set();
    // 全选/取消全选当前页
    function toggleSelectAll() {
        const isChecked = $('#selectAll').prop('checked');
        const currentPageIds = [];
        $('.row-checkbox').each(function() {
            currentPageIds.push($(this).data('id'));
        });

        // 更新全局选择状态
        if(isChecked) {
            currentPageIds.forEach(id => globalSelectedIds.add(id));
        }

        // 更新当前页所有复选框状态
        $('.row-checkbox').prop('checked', isChecked);

        updateSelectedCount();
    }

    // 更新单行选择状态
    function updateRowSelection(checkbox) {
        const id = $(checkbox).data('id');
        const isChecked = $(checkbox).prop('checked');
        // 更新全局选择状态
        if(isChecked) {
            globalSelectedIds.add(id);
        } else {
            globalSelectedIds.delete(id);
        }

        // 更新全选复选框状态
        updateSelectAllStatus();
        updateSelectedCount();
    }

    // 更新全选复选框状态（仅针对当前页）
    function updateSelectAllStatus() {
        const allCurrentPageChecked = $('.row-checkbox').length === $('.row-checkbox:checked').length;
        console.log(allCurrentPageChecked)
        $('#selectAll').prop('checked', allCurrentPageChecked);
    }

    // 获取所有选中的ID（跨分页）
    function getSelectedIds() {
        return Array.from(globalSelectedIds);
    }

    // 更新选中计数显示
    function updateSelectedCount() {
        $('#selectedCount').text('已选择 ' + globalSelectedIds.size + ' 项');
    }

    // 在渲染表格时恢复选择状态
    // 清空所有选择
    function clearAllSelections() {
        globalSelectedIds.clear();
        $('.row-checkbox').prop('checked', false);
        $('#selectAll').prop('checked', false);
        updateSelectedCount();
    }
    // 页面加载时初始化
    $(document).ready(function () {
        showErrorCollectionByPage();
        getErrorCollectionCount();
    });

    // 分页展示错题集数据
    function showErrorCollectionByPage() {
        $.ajax({
            url: "/WrongQuestion/ShowErrorCollectionByPage",
            type: "post",
            dataType: "json",
            data: {
                student,
                page: currentPage,
                pageSize: pageSize
            },
            success: function (res) {
                if (res.code === 200) {
                    const data = res.data;
                    const tbody = $("#errorNotesTableBody");
                    tbody.empty();
                    data.forEach(item => {
                        tbody.append(`
                <tr>
                  <td><input type="checkbox" class="row-checkbox"
                      data-id="${item.id}"
                      ${globalSelectedIds.has(item.id) ? 'checked' : ''}
                      onclick="updateRowSelection(this)"></td>
                  <td>${item.id}</td>
                  <td>${item.question}</td>
                  <td>${item.correctAnswer}</td>
                  <td>${item.errorReason}</td>
                  <td>${item.userAnswer}</td>
                  <td>
                    <button class="action-btn" onclick="viewError(${item.id})">
                      <i class="fas fa-eye"></i> 查看
                    </button>
                    <button class="action-btn delete-btn" onclick="deleteErrorCollection(${item.id})">
                      <i class="fas fa-trash"></i> 删除
                    </button>
                  </td>
                </tr>
              `);
                        updateSelectAllStatus()
                    });
                } else {
                    alert("分页展示错题集失败：" + res.msg);
                }
            },
            error: function () {
                alert("分页展示错题集信息失败，请联系管理员");
            }
        });
    }

    // 获取错题数量
    function getErrorCollectionCount() {
        $.ajax({
            url: "/WrongQuestion/GetErrorCollectionCount",
            type: "post",
            dataType: "json",
            data: {
                student
            },
            success: function (res) {
                if (res.code === 200) {
                    totalItems = res.data;
                    totalPages = Math.ceil(totalItems / pageSize);
                    renderPagination();
                } else {
                    alert("获取错题数量失败：" + res.msg);
                }
            },
            error: function () {
                alert("获取错题数量出错，请联系管理员");
            }
        });
    }

    // 删除错题
    function deleteErrorCollection(id) {
        if (confirm("确定删除该错题？")) {
            $.ajax({
                url: "/WrongQuestion/DeleteErrorCollection",
                type: "delete",
                dataType: "json",
                data: {
                    id
                },
                success: function (res) {
                    if (res.code === 200) {
                        // 删除后重新加载数据
                        totalItems--;
                        totalPages = Math.ceil(totalItems / pageSize);
                        currentPage = currentPage > totalPages ? totalPages : currentPage;
                        showErrorCollectionByPage();
                        renderPagination();
                    } else {
                        alert("删除错题失败：" + res.msg);
                    }
                },
                error: function () {
                    alert("删除错题出错，请联系管理员");
                }
            });
        }
    }

    // 查看错题弹层（从表格 DOM 取数据）
    function viewError(id) {
        // 根据 id 找到表格中对应的行
        const $targetTr = $(`tr:has(td:nth-child(1):contains('${id}'))`);
        if ($targetTr.length === 0) {
            alert("未找到该错题数据");
            return;
        }

        // 从表格行中提取数据
        const item = {
            id: id,
            question: $targetTr.find("td:eq(1)").text(),
            correct_answer: $targetTr.find("td:eq(2)").text(),
            error_reason: $targetTr.find("td:eq(3)").text(),
            user_answer: $targetTr.find("td:eq(4)").text()
        };

        // 填充弹层内容
        $("#viewNoteId").text(item.id);
        $("#viewQuestion").text(item.question);
        $("#viewCorrectAnswer").text(item.correct_answer);
        $("#viewErrorReason").text(item.error_reason);
        $("#viewUserAnswer").text(item.user_answer);

        // 显示弹层
        $("#viewErrorNoteModal").css("display", "flex");
    }

    // 关闭弹层
    function closeModal() {
        $("#viewErrorNoteModal").css("display", "none");
    }

    // 渲染分页器
    // 渲染分页器（改进版，支持大量页码时的截断显示）
    function renderPagination() {
        const pageNumberDiv = $("#pageNumber");
        pageNumberDiv.empty();

        const maxVisiblePages = 5; // 最多显示的页码数量（不包括首尾和省略号）
        const halfVisible = Math.floor(maxVisiblePages / 2);
        let startPage = 1;
        let endPage = totalPages;

        if (totalPages > maxVisiblePages + 2) { // 需要截断显示
            // 计算起始和结束页码
            startPage = Math.max(1, currentPage - halfVisible);
            endPage = Math.min(totalPages, currentPage + halfVisible);

            // 调整以保证显示足够的页码
            if (currentPage <= halfVisible) {
                endPage = maxVisiblePages;
            } else if (currentPage >= totalPages - halfVisible) {
                startPage = totalPages - maxVisiblePages + 1;
            }
        }

        // 添加页码按钮
        if (startPage > 1) {
            // 添加第一页
            const btn1 = $(`<button class="page-btn ${1 === currentPage ? 'active' : ''}">1</button>`);
            btn1.click(() => goToPage(1));
            pageNumberDiv.append(btn1);

            if (startPage > 2) {
                // 添加省略号
                pageNumberDiv.append('<span class="ellipsis">...</span>');
            }
        }

        // 添加中间页码
        for (let i = startPage; i <= endPage; i++) {
            const btn = $(`<button class="page-btn ${i === currentPage ? 'active' : ''}">${i}</button>`);
            btn.click(() => goToPage(i));
            pageNumberDiv.append(btn);
        }

        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                // 添加省略号
                pageNumberDiv.append('<span class="ellipsis">...</span>');
            }
            // 添加最后一页
            const btnLast = $(`<button class="page-btn ${totalPages === currentPage ? 'active' : ''}">${totalPages}</button>`);
            btnLast.click(() => goToPage(totalPages));
            pageNumberDiv.append(btnLast);
        }
        $('#selectAll').prop('checked', false);
    }
    // 跳转页码
    function goToPage(page) {
        if (page < 1 || page > totalPages) return;
        currentPage = page;
        showErrorCollectionByPage();
        renderPagination();
    }

    // 改变每页条数
    function changePageSize() {
        pageSize = parseInt($(".page-size-select").val());
        currentPage = 1;
        getErrorCollectionCount();
        showErrorCollectionByPage();
    }

    // 页码跳转（输入框）
    function jumpToPage() {
        const page = parseInt($("#pageJump").val());
        if (isNaN(page) || page < 1 || page > totalPages) {
            alert("请输入有效页码");
            return;
        }
        goToPage(page);
    }

    // 显示生成试卷模态框
    function showGeneratePaperModal() {
        // 加载所有错题以供选择
        loadAllErrorQuestions();
        $("#generatePaperModal").css("display", "block");
    }

    // 关闭生成试卷模态框
    function closeGenerateModal() {
        $("#generatePaperModal").css("display", "none");
    }

    // 加载所有错题到选择列表
    function loadAllErrorQuestions() {
        $.ajax({
            url: "/WrongQuestion/GetAllErrorQuestions",
            type: "post",
            dataType: "json",
            data: { student },
            success: function (res) {
                if (res.code === 200) {
                    const data = res.data;
                    const selectionDiv = $("#questionSelection");
                    selectionDiv.empty();

                    data.forEach(item => {
                        selectionDiv.append(`
                        <div class="question-item">
                            <input type="checkbox" id="q_${item.id}" value="${item.id}" checked>
                            <label class="question-text" for="q_${item.id}">
                                ${item.question.substring(0, 50)}${item.question.length > 50 ? '...' : ''}
                            </label>
                        </div>
                    `);
                    });

                    // 设置最大题目数量
                    $("#questionCount").attr("max", data.length);
                    if (data.length < 10) {
                        $("#questionCount").val(data.length);
                    }
                } else {
                    alert("加载错题列表失败：" + res.msg);
                }
            },
            error: function () {
                alert("加载错题列表出错，请联系管理员");
            }
        });
    }

    // 生成试卷
    function generatePaper() {
        const title = $("#paperTitle").val().trim();
        if (!title) {
            alert("请输入试卷标题");
            return;
        }

        const count = parseInt($("#questionCount").val());
        const type = $("#paperType").val();

        // 获取选中的题目ID
        const selectedQuestions = [];
        $(".question-item input[type='checkbox']:checked").each(function() {
            selectedQuestions.push($(this).val());
        });

        if (selectedQuestions.length === 0) {
            alert("请至少选择一道题目");
            return;
        }

        if (count > selectedQuestions.length) {
            alert("选择的题目数量不能超过已选题目数量");
            return;
        }

        // 如果需要随机选择指定数量的题目
        let finalQuestions = selectedQuestions;
        if (count < selectedQuestions.length) {
            // 随机选择指定数量的题目
            finalQuestions = shuffleArray(selectedQuestions).slice(0, count);
        }

        // 调用API生成试卷
        $.ajax({
            url: "/WrongQuestion/GeneratePaper",
            type: "post",
            dataType: "json",
            data: {
                student,
                title,
                questionIds: finalQuestions.join(","),
                type
            },
            success: function (res) {
                if (res.code === 200) {
                    // 下载生成的试卷
                    downloadPaper(res.data.paperId, title);
                    closeGenerateModal();
                } else {
                    alert("生成试卷失败：" + res.msg);
                }
            },
            error: function () {
                alert("生成试卷出错，请联系管理员");
            }
        });
    }

    // 下载试卷
    function downloadPaper(paperId, title) {
        // 这里可以使用window.open或者创建一个隐藏的iframe来下载
        window.open(`/WrongQuestion/DownloadPaper?paperId=${paperId}&title=${encodeURIComponent(title)}`);
    }

    // 辅助函数：打乱数组顺序
    function shuffleArray(array) {
        const newArray = [...array];
        for (let i = newArray.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
        }
        return newArray;
    }
    $("#addNoteBtn").on("click",function (){
        var list = getSelectedIds()
        $.cookie("wronglist",list)
        location.href="WrongQuestionExam"
    })
</script>
</body>

</html>